from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from videos.models import Video
from subprocess import call
from django.core.files.base import ContentFile
from photologue.models import Photo
class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--reset', '-r', action='store_true', dest='reset', help='Convert videos even if they existed'),
    )

    help = ('Converts video to the required web format.')
    args = ''

    requires_model_validation = True
    can_import_settings = True

    def handle(self, *args, **options):
        return convert(options)

def convert(options):
    """
    Converts the video to flv format using ffmpeg and creates a stil for preview
    """
    reset = options.get('reset', None)

    print 'Converting videos, this may take a while...'

    for video in Video.objects.all():
        print 'Original' + video.original_video.file.name
        filename =  video.title_slug
        input = video.original_video.file.name
        #Convert the vidoes using ffmpeg
        if video.video:
        #    pass
        #else:
            print call('ffmpeg -i %s -sameq %s.flv' % (input, filename), shell=True)
            #Open the file and put it in a friendly format for image save
            f = open('%s.flv' % filename, 'r')
            filecontent = ContentFile(f.read())
            video.video.save('%s.flv' % filename,filecontent , save=True)
            f.close()
            if video.image:
                pass
            else:
                print call('ffmpeg -i %s.flv -sameq %s%sd.jpg' % (filename, filename, '%'), shell=True)             
                f = open('%s1.jpg' % filename, 'r')
                filecontent = ContentFile(f.read())
                image = Photo(title=filename, title_slug=filename)    
                image.image.save('%s1.jpg' % filename,filecontent , save=True)
                image.save()
                video.image=image
                #Clean the flv files left around
        call('rm *.flv *.jpg', shell=True)
        video.save()
        print 'Converted' + video.video.file.name
